#include <stdio.h>
#include <stdlib.h>

#define MAX_NAME_LEN 50

typedef struct {
    int id;
    char name[MAX_NAME_LEN];
    float score;
} Student;

void loadStudents(FILE *fp, Student **students, int *count) {
    fseek(fp, 0, SEEK_END);
    long fileSize = ftell(fp);
    fseek(fp, 0, SEEK_SET);

    *count = fileSize / sizeof(Student);
    *students = (Student *)malloc(fileSize);

    if (*students == NULL) {
        perror("Memory allocation failed");
        exit(EXIT_FAILURE);
    }

    fread(*students, sizeof(Student), *count, fp);
}

void displayStudents(Student *students, int count) {
    for (int i = 0; i < count; i++) {
        printf("ID: %d, Name: %s, Score: %.2f\n", students[i].id, students[i].name, students[i].score);
    }
}

int main() {
    FILE *fp = fopen("students.dat", "rb");
    if (fp == NULL) {
        perror("Failed to open file");
        return EXIT_FAILURE;
    }

    int stuCount = 0;  // 总共有多少条学生信息
    Student *students = NULL;

    loadStudents(fp, &students, &stuCount);
    fclose(fp);

    printf("Total Students: %d\n", stuCount);
    displayStudents(students, stuCount);

    free(students);  // 释放分配的内存
    return 0;
}
